import { Injectable, OnApplicationBootstrap } from '@nestjs/common'
import { ipcMain } from 'electron'
import { IpcRegistry } from '@main/decorator/registry'
import { ModuleRef } from '@nestjs/core'

@Injectable()
export class IpcRegistrarService implements OnApplicationBootstrap {
  constructor(private readonly moduleRef: ModuleRef) {}

  onApplicationBootstrap() {
    const registry = IpcRegistry.getInstance()
    const methods = registry.getPendingMethods()

    for (const { targetClass, methodName, methodKey } of methods) {
      const module = Reflect.getMetadata('ipc:module', targetClass) || targetClass.name
      const channel = `${module}.${methodKey}`

      ipcMain.handle(channel, async (_event, ...args) => {
        try {
          const instance = this.moduleRef.get(targetClass, { strict: false })
          if (!instance) throw new Error(`Instance not found: ${targetClass.name}`)
          return await instance[methodName](...args)
        } catch (err: any) {
          console.error(`[IPC] 执行失败 ${channel}:`, err)
          return { success: false, error: err.message }
        }
      })
    }

    ipcMain.handle('listApiModules', () => registry.getModules())

    console.log('[IPC Registrar] 已注册模块:', registry.getModules())
  }
}
